package com.itheima.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderInfoVo;
import com.itheima.service.OrderService;
import com.itheima.utils.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    JedisUtil jedisUtil;
    //failover 出错会重试(默认会重试2次)
    //failfast 出错不在调用
    //幂等性
    @Reference(cluster = "failfast")
    OrderService orderService;

    /**
     * 1、form表单提交数据的格式 （name=jack&age=18&address=shangshou） 后端用对象接收不需要加注解
     * 2、页面传的是json数据，后端使用map 或者 pojo时 需要加@RequestBody
     * 3、基本类型 & 数组 & MultipartFile 只要保持页面的参数名称和controller方法形参一致就不用加@RequestParam
     * 4、List 不管名字一不一样 必须加@RequestParam
     *
     * @return
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody OrderInfoVo orderInfoVo,HttpServletRequest request) {
        String token = request.getHeader("token");
        if (null == token) {
            return Result.error("401");
        }
        String member = jedisUtil.get(token);
        if (member == null) {
            return Result.error("401");
        }

        String pageToken = orderInfoVo.getToken();
        if (null == pageToken) {
            return Result.error("非法请求");
        }

        Long count = jedisUtil.delete(pageToken);//单线程，删除请求需要排队
        if (count == 0) {
            return Result.error("非法请求,删除token失败");
        }

        //校验验证码
        String validateCode = orderInfoVo.getValidateCode();
        String telephone = orderInfoVo.getTelephone();
        String redisCode = jedisUtil.get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if (StrUtil.isBlank(redisCode) || !redisCode.equals(validateCode)) {
            return Result.error("验证码错误");
        }

        //把预约类型改成微信预约
        orderInfoVo.setOrderType(Order.ORDERTYPE_WEIXIN);

        Result result = null;
        result = orderService.submit(orderInfoVo);
        return result;

    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        Map map = orderService.findById(id);
        return Result.success("", map);
    }

    @RequestMapping("/getToken")
    public Result getToken() {
        String token = UUID.randomUUID().toString();
        jedisUtil.add(token, 500, token);
        return Result.success("", token);
    }
}
